package com.unicdata.ai.demo_2af.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.unicdata.ai.demo_2af.annotation.Log;
import com.unicdata.ai.demo_2af.common.entity.Role;
import com.unicdata.ai.demo_2af.common.exception.BusinessException;
import com.unicdata.ai.demo_2af.common.result.Result;
import com.unicdata.ai.demo_2af.common.vo.PermissionAssignRequest;
import com.unicdata.ai.demo_2af.service.RoleService;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.Date;

/**
 * 角色控制器
 *
 * @author lhn
 * @date 2025/06/25 17:06
 * @since 1.0.0
 **/
@RestController
@RequestMapping("/role")
public class RoleController {

    @Autowired
    private RoleService roleService;

    /**
     * 角色列表
     */
    @GetMapping("/list")
    @RequiresPermissions("role:view")
    @Log("查询角色列表")
    public Result<IPage <Role>> list(@RequestParam(defaultValue = "1") Integer current,
                                     @RequestParam(defaultValue = "10") Integer size,
                                     @RequestParam(required = false) String roleName) {
        Page<Role> page = new Page <>(current, size);
        LambdaQueryWrapper<Role> queryWrapper = new LambdaQueryWrapper <>();

        // 按角色名称模糊查询
        if (StringUtils.isNotBlank(roleName)) {
            queryWrapper.like(Role::getRoleName, roleName);
        }

        IPage<Role> rolePage = roleService.page(page, queryWrapper);
        return Result.success(rolePage);
    }

    /**
     * 获取角色详情
     */
    @GetMapping("/{roleId}")
    @RequiresPermissions("role:view")
    public Result<Role> getRole(@PathVariable Long roleId) {
        if (roleId == null) {
            throw new BusinessException("角色ID不能为空");
        }

        Role role = roleService.getById(roleId);
        if (role == null) {
            return Result.error("角色不存在");
        }

        return Result.success(role);
    }

    /**
     * 新增角色
     */
    @PostMapping
    @RequiresPermissions("role:add")
    @Log("新增角色")
    public Result<Void> add(@RequestBody @Valid Role role) {
        if (StringUtils.isBlank(role.getRoleName())) {
            throw new BusinessException("角色名称不能为空");
        }
        if (StringUtils.isBlank(role.getRoleCode())) {
            throw new BusinessException("角色编码不能为空");
        }

        // 检查角色编码是否已存在
        Role existRole = roleService.getRoleByCode(role.getRoleCode());
        if (existRole != null) {
            return Result.error("角色编码已存在");
        }

        role.setCreateTime(new Date());
        role.setUpdateTime(new Date());
        boolean success = roleService.save(role);

        if (success) {
            return Result.success(null, "角色添加成功");
        } else {
            return Result.error("角色添加失败");
        }
    }

    /**
     * 更新角色
     */
    @PutMapping
    @RequiresPermissions("role:edit")
    @Log("更新角色")
    public Result<Void> update(@RequestBody @Valid Role role) {
        if (role.getId() == null) {
            throw new BusinessException("角色ID不能为空");
        }
        if (StringUtils.isBlank(role.getRoleName())) {
            throw new BusinessException("角色名称不能为空");
        }

        // 检查角色是否存在
        Role existRole = roleService.getById(role.getId());
        if (existRole == null) {
            return Result.error("角色不存在");
        }

        // 不允许修改角色编码
        role.setRoleCode(existRole.getRoleCode());
        role.setUpdateTime(new Date());
        boolean success = roleService.updateById(role);

        if (success) {
            return Result.success(null, "角色更新成功");
        } else {
            return Result.error("角色更新失败");
        }
    }

    /**
     * 删除角色
     */
    @DeleteMapping("/{roleId}")
    @RequiresPermissions("role:delete")
    @Log("删除角色")
    public Result<Void> delete(@PathVariable Long roleId) {
        if (roleId == null) {
            throw new BusinessException("角色ID不能为空");
        }

        Role role = roleService.getById(roleId);
        if (role == null) {
            return Result.error("角色不存在");
        }

        // 不允许删除管理员角色
        if ("ADMIN".equals(role.getRoleCode())) {
            return Result.error("不能删除管理员角色");
        }

        boolean success = roleService.removeById(roleId);

        if (success) {
            return Result.success(null, "角色删除成功");
        } else {
            return Result.error("角色删除失败");
        }
    }

    /**
     * 分配权限
     */
    @PostMapping("/assignPermissions")
    @RequiresPermissions("role:edit")
    @Log("分配角色权限")
    public Result <Void> assignPermissions(@RequestBody @Valid PermissionAssignRequest request) {
        Long roleId = request.getRoleId();
        if (roleId == null) {
            throw new BusinessException("角色ID不能为空");
        }

        try {
            boolean success = roleService.assignPermissions(roleId, request.getPermissionIds());
            if (success) {
                return Result.success(null, "权限分配成功");
            } else {
                return Result.error("权限分配失败");
            }
        } catch (BusinessException e) {
            return Result.error(e.getMessage());
        }
    }

}